#include "InfoCarMgr.h"

InfoCarMgr::InfoCarMgr()
{
	m_pReceiveSocket = new QUdpSocket;
	if (m_pReceiveSocket->bind(QHostAddress::AnyIPv4, 1222))
	{
		m_pReceiveSocket->joinMulticastGroup(QHostAddress("224.4.5.6"));
		//m_pUdpSocket->moveToThread(this);
		connect(m_pReceiveSocket, &QUdpSocket::readyRead, this, &InfoCarMgr::slotReadyRead);
	}
	else
	{
		delete m_pReceiveSocket;
		m_pReceiveSocket = NULL;
	}


}


InfoCarMgr::~InfoCarMgr()
{
	this->quit();
	this->wait();
}

void InfoCarMgr::run()
{
	m_pSendSocket = new QUdpSocket;
	if (!m_pSendSocket->bind(QHostAddress::AnyIPv4))
	{
		delete m_pSendSocket;
		m_pSendSocket = NULL;
	}
	while (true)
	{
		m_mutex.lock();
		if (m_listSendBytes.isEmpty())
		{
			m_mutex.unlock();
			msleep(300);
			continue;
		}
		QByteArray bytes = m_listSendBytes.front();
		m_listSendBytes.pop_front();
		m_mutex.unlock();
		if (m_pSendSocket)
		{
			qint64 ret= m_pSendSocket->writeDatagram(bytes, QHostAddress("224.4.5.6"), 1223);
			m_pSendSocket->writeDatagram(bytes, QHostAddress("224.4.5.6"), 5656);
			msleep(50);
		}
		bytes.clear();
	}	
}

void InfoCarMgr::slotReadyRead()
{
	while (m_pReceiveSocket->hasPendingDatagrams()) {
		QByteArray datagram;
		datagram.resize(m_pReceiveSocket->pendingDatagramSize());
		QHostAddress sender;
		quint16 senderPort;

		int ret = m_pReceiveSocket->readDatagram(datagram.data(), datagram.size(),
			&sender, &senderPort);
		if(ret > 0)
			receiveBytes(datagram);
	}
}

void InfoCarMgr::addSendBytes(const QByteArray& bytes)
{
	QMutexLocker locker(&m_mutex);
	if (bytes.isEmpty())
		return;
	m_listSendBytes.push_back(bytes);
}
